package com.itheima.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import com.itheima.utils.TliasException;
import com.sun.xml.bind.v2.TODO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;

/**
 * @author: zhengsuyang
 * @Desc:
 * @create: 2025-09-05 19:52
 **/
@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogService empLogService;
    @Autowired
    private DeptService deptService;
    // 普通手动分页
/*    @Override
    public PageResult<Emp> queryEmpList(Integer page, Integer pageSize) {
        // 获取总记录数
        long total = empMapper.getTotal();
        // 获取索引
        Integer index = (page - 1) *pageSize;
        // 获取数据列表
        List<Emp> empList =  empMapper.getEmpList(index,pageSize);
        // 创建分页对象
        PageResult<Emp> pageResult = new PageResult<>();
        // 封装分页结果
        pageResult.setRows(empList);
        pageResult.setTotal(total);
        return pageResult;
    }*/
/*    @Override
    public PageResult<Emp> queryEmpList(Integer pageNum, Integer pageSize) {
        // 1.设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        // 2.调用查询所有数据
        Page<Emp> emps = (Page<Emp>) empMapper.findAllEmpList();
        // 封装数据
        PageResult<Emp> pageResult = new PageResult<>(emps.getTotal(), emps.getResult());
        return pageResult;
    }*/

    /*    @Override
        public PageResult<Emp> conditionQueryEmpList(Integer page, Integer pageSize, String name, Integer gender, Integer job, LocalDate begin, LocalDate end) {
            // 1.设置分页参数
            PageHelper.startPage(page,pageSize);
            // 2.调用条件查询数据
            Page<Emp> emps = (Page<Emp>) empMapper.conditionQueryEmpList(name,gender,job,begin,end);
            // 封装数据
            PageResult<Emp> pageResult = new PageResult<>();
            pageResult.setTotal(emps.getTotal());
            pageResult.setRows(emps.getResult());
            return pageResult;
        }*/
   /* @Override
    public PageResult<Emp> conditionQueryEmpList(EmpQueryParam empQueryParam) {
        // 1.设置分页参数
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());
        // 调用条件查询数据查询
        List<Emp> emps = empMapper.conditionQueryEmpLists(empQueryParam);
        // 封装数据
        PageInfo<Emp> pageInfo = new PageInfo<>(emps);
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getList());
    }*/

    /**
     * 添加员工
     *
     * @param emp
     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void addEmp(Emp emp){
//        // 1.添加员工基本信息
//        emp.setCreateTime(LocalDateTime.now());
//        emp.setUpdateTime(LocalDateTime.now());
//        emp.setPassword("123456");
//        empMapper.addEmp(emp);
////        //记录操作日志
////        EmpLog empLog = new EmpLog(null, LocalDateTime.now(), emp.toString());
////        empLogService.insertLog(empLog);
/////*        if(true)
////            throw new Exception("异常....");*/
////        int i = 1/0;
//        // 2.添加员工工作经历
//        List<EmpExpr> exprList = emp.getExprList();
//        if (exprList != null && exprList.size() > 0) {
//            exprList.forEach(empExpr ->
//                    empExpr.setEmpId(emp.getId()));
//            empExprMapper.addBatchExpr(exprList);
//        }
//
//
//    }

    /**
     * 修改员工
     * 员工信息 + 工作经历
     * @param emp
     *//*
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        // 1.先修改员工基本信息
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateEmpById(emp);
        // 2.修改员工工作经历
        // 2.1先删除员工工作经历
        empExprMapper.delExprByIds(Arrays.asList(emp.getId()));
        // 2.2再新增员工工作经历
        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && exprList.size() > 0) {
            exprList.forEach(empExpr ->
                    empExpr.setEmpId(emp.getId()));
            empExprMapper.addBatchExpr(exprList);
        }

    }
*/
    /**
     * 统计各个职位的员工人数
     *
     * @return
     */
    @Override
    public JobOption getEmpJobData() {
       List<Map<String,Object>> mapList =empMapper.getEmpJobData();
       List jobList = new ArrayList();
       List totalList = new ArrayList();
        for (Map<String, Object> map : mapList) {
            jobList.add(map.get("jobName"));
            totalList.add(map.get("total"));
        }
       /* List<Object> jobList = mapList.stream().map(new Function<Map<String, Object>, Object>() {
            @Override
            public Object apply(Map<String, Object> stringIntegerMap) {
                return stringIntegerMap.get("jobName");
            }
        }).toList();
        List<Object> totalList = mapList.stream().map(dataMap -> dataMap.get("total")).toList();*/
        JobOption jobOption = new JobOption(jobList,totalList);
        return jobOption;
    }

    /**
     * 统计各个性别的员工人数
     *
     * @return
     */
    @Override
    public List<Map> getEmpGenderData() {
       List<Map> mapList  = empMapper.getEmpGenderData();
       return mapList;
    }

    /**
     * 统计各个班级的学生人数
     */
    @Override
    public StudentCountOption getStudentCountData() {
      List<Map<String,Object>> mapList = empMapper.getStudentCountData();
        List<Object> clazzNameList = mapList.stream().map(listName -> listName.get("clazzName")).toList();
        List<Object> totalList = mapList.stream().map(listTotal -> listTotal.get("total")).toList();
        return new StudentCountOption(clazzNameList,totalList);
    }

    /**
     * 统计各个学历的学生人数
     *
     * @return
     */
    @Override
    public List<Map> getStudentDegreeData() {
       List<Map> mapList =empMapper.getStudentDegreeData();
       return mapList;
    }

    /**
     * 查询全部员工
     *
     * @return
     *//*
    @Override
    public List<Emp> queryList() {
        return empMapper.queryList();
    }
*/
    /**
     * 登录功能
     *
     * @param empDto
     * @return
     */
/*    @Override
    public LoginInfo login(EmpDto empDto) {
        Emp emp = empMapper.finaEmpByPasswordAndUsername(empDto);
        if (emp==null){
            // 自定义异常
            throw  new TliasException("用户名或密码错误！");
        }
        Integer id = emp.getId();
        String name = emp.getName();
        String username = emp.getUsername();
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setId(id);
        loginInfo.setName(name);
        loginInfo.setUsername(username);
        // 设置token
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",emp.getId());
        claims.put("name",emp.getName());
        // 获取token
        String jwt = JwtUtils.generateJwt(claims);
        // 设置
        loginInfo.setToken(jwt);
        return loginInfo;
    }*/
    @Override
    public LoginInfo login(EmpDto empDto) {
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(empDto.getUsername()),Emp::getUsername,empDto.getUsername());
        queryWrapper.eq(StrUtil.isNotBlank(empDto.getPassword()),Emp::getPassword,empDto.getPassword());
        Emp emp = this.getOne(queryWrapper);
        if (emp==null){
            // 自定义异常
            throw  new TliasException("用户名或密码错误！");
        }
        Integer id = emp.getId();
        String name = emp.getName();
        String username = emp.getUsername();
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setId(id);
        loginInfo.setName(name);
        loginInfo.setUsername(username);
        // 设置token
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",emp.getId());
        claims.put("name",emp.getName());
        // 获取token
        String jwt = JwtUtils.generateJwt(claims);
        // 设置
        loginInfo.setToken(jwt);
        return loginInfo;
    }

    /**
     * 分页查询 + mybatisplus
     *
     * @param empQueryParam
     * @return
     */
    @Override
    public PageResult<Emp> conditionQueryEmpList(EmpQueryParam empQueryParam) {
        // 1.获取分页参数
        Page<Emp> page = new Page<>(empQueryParam.getPage(),empQueryParam.getPageSize());
        // 2.设置分页查询参数
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(empQueryParam.getName()),Emp::getName,empQueryParam.getName());
        queryWrapper.eq(empQueryParam.getGender()!=null,Emp::getGender,empQueryParam.getGender());
        queryWrapper.between(empQueryParam.getBegin()!=null&&empQueryParam.getEnd()!=null,Emp::getEntryDate,empQueryParam.getBegin(),empQueryParam.getEnd());
        // 3.执行查询
        page = this.page(page, queryWrapper);
        List<Emp> empList = page.getRecords();
        empList.forEach(emp -> {
            Integer deptId = emp.getDeptId();
            if(deptId!=null) {
                Dept dept = deptService.getById(deptId);
                if (dept != null) {
                    emp.setDeptName(dept.getName());
                }
            }
        });
        // 4.返回数据
        return new PageResult<>(page.getTotal(),page.getRecords());
    }

    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @Override
    public Emp queryEmpAndExpr(Integer id) {
        Emp emp = this.getById(id);
        LambdaQueryWrapper<EmpExpr> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmpExpr::getEmpId, id);
        List<EmpExpr> exprList = empExprMapper.selectList(queryWrapper);
        emp.setExprList(exprList);
        return emp;
    }

    /**
     * 新增员工和经历 + mybatisPlus
     *
     * @param emp
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addEmpAndExpr(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        emp.setCreateTime(LocalDateTime.now());
        emp.setPassword("123456");
        this.save(emp); // 保存之后有id
        Integer empId = emp.getId();
        // 新增员工经历
        if (empId!=null){
            List<EmpExpr> exprList = empExprMapper.selectByIds(Arrays.asList(empId));
            if (exprList != null && exprList.size() > 0){
                exprList.forEach(empExpr -> {
                    empExpr.setEmpId(empId);
                });
            }
        }
    }

    /**
     * 删除员工和经历 + mybatisPlus
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer delEmpById(List<Integer> ids) {
        // 删除员工
        this.removeBatchByIds(ids);
        // 删除员工经历
        LambdaQueryWrapper<EmpExpr> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(EmpExpr::getEmpId,ids);
        int num = empExprMapper.delete(queryWrapper);
        if (num>0)
            return 1;
        else
            return 0;
    }

    /**
     * 修改员工和员工经历 + mybatisPlus
     *
     * @param emp
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmpAndExpr(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        // 修改员工
        this.updateById(emp);
        // 删除员工经历
        Integer empId = emp.getId();
        empExprMapper.deleteById(empId);
        // 新增员工经历
        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(expr -> {
            expr.setEmpId(empId);
        });
            empExprMapper.insert(exprList);
        }


    /**
     * 批量删除员工
     * @param ids
     * @return
     *//*
    @Override
    public Integer delEmpById(List<Integer> ids) {
        Integer num = empMapper.delEmpByIds(ids);
        empExprMapper.delExprByIds(ids);
        return num;
    }

    *//**
     * 根据id查询员工
     * @param id
     * @return
     *//*
    @Override
    public Emp queryEmpById(Integer id) {
        Emp emp = empMapper.queryEmpById(id);
        List<EmpExpr> exprList = empExprMapper.queryExprById(id);
        emp.setExprList(exprList);
        return emp;
    }*/


}
